﻿using System;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Volo.Abp.DependencyInjection;

namespace Joy.Erp.BasicArchives.Core.UniqueCodes
{
    public class UniqueCodeSetter : IUniqueCodeSetter, ITransientDependency
    {
        protected readonly UniqueCodeOptions _options;
        protected IServiceProvider ServiceProvider;

        public UniqueCodeSetter(IOptions<UniqueCodeOptions> options, IServiceProvider serviceProvider)
        {
            _options = options.Value;
            ServiceProvider = serviceProvider;
        }

        public void SetCode(IUniqueCode entity, string uniqueCodeConfigration)
        {
            if (string.IsNullOrEmpty(uniqueCodeConfigration)) return;

            var configrationObject = JsonConvert.DeserializeObject<UniqueCodeConfigrationObject>(uniqueCodeConfigration);
            if (!configrationObject.AutoCode) return;
            if (configrationObject.SegmentConfigrations == null || configrationObject.SegmentConfigrations.Count <= 0) return;

            var code = string.Empty;
            foreach (var segmentConfigration in configrationObject.SegmentConfigrations)
            {
                var segmentConfigrationArray = segmentConfigration.Split("::");
                var key = segmentConfigrationArray[0];
                var configration = segmentConfigrationArray[1];

                var segmentType = _options.GetOrNull(key);
                var segment = ServiceProvider.GetRequiredService(segmentType) as ISegment;
                segment.Init(configration);

                code = $"{code}{segment.GetCode(entity)}";                
            }
            entity.Code = code;
        }
    }
}
